package template;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.mwe.core.WorkflowContextDefaultImpl;
import org.eclipse.emf.mwe.core.issues.IssuesImpl;
import org.eclipse.xpand2.Generator;
import org.eclipse.xpand2.output.Outlet;
import org.eclipse.xpand2.output.Output;
import org.eclipse.xpand2.output.OutputImpl;
import org.eclipse.xtend.typesystem.emf.EmfMetaModel;

import betportal.BetportalPackage;
import betportal.Portal;

public class XPandRunner {

	public XPandRunner() {
	}

	public void generateProject(Portal portal, String ejbProjectName, String earProjectName)
			throws CoreException {

		IWorkspace ws = ResourcesPlugin.getWorkspace();
		IProject project = ws.getRoot().getProject(ejbProjectName);

		EmfMetaModel mm = new EmfMetaModel(BetportalPackage.eINSTANCE);
		Output output = new OutputImpl();
		Outlet outlet = new Outlet(project.getLocation().toOSString()
				+ "/ejbModule");
		output.addOutlet(outlet);

		Generator gen = new Generator();
		gen.addMetaModel(mm);
		gen.setExpand("template::portal::main FOR portal");
		gen.setOutput(output);

		WorkflowContextDefaultImpl wfc = new WorkflowContextDefaultImpl();
		wfc.set("portal", portal);

		gen.invoke(wfc,
				new org.eclipse.emf.mwe.core.monitor.NullProgressMonitor(),
				new IssuesImpl());

		// infinite depth refresh
		project.refreshLocal(2, null);

		if (!earProjectName.matches(""))
			ws.getRoot().getProject(earProjectName).refreshLocal(2, null);
	}
}
